/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package util.ejb;

import entities.tools.FilledForm;
import entities.tools.Form;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Bean used for the management of the FilledForm entity. Contains crud
 * operations, search operations, and other useful tools
 *
 * @author Marek
 */
@Stateless
public class FilledFormBean implements FilledFormBeanInterface {

    @PersistenceContext(name = "test", unitName = "JEE-study-warPU")
    private EntityManager em;

    /**
     * Method creates new FilledForm instance
     *
     * @return new FilledForm instance
     */
    @Override
    public FilledForm createFilledForm() {
        FilledForm filledForm = new FilledForm();
        em.persist(filledForm);
        return filledForm;
    }

    /**
     * Method deletes specified by detachedFilledForm entity
     *
     * @param detachedFilledForm
     * @return true if operation succeeded, false - if not
     */
    @Override
    public boolean deleteFilledForm(FilledForm detachedFilledForm) {
        FilledForm attachedFilledForm = em.find(FilledForm.class, detachedFilledForm.getId());
        if (null == attachedFilledForm) {
            System.out.println("FilledFormBean:deleteFilledForm():FilledForm, you have specified, doesn't exist in the database!");
            return false;
        }
        //TODO: Check if with all answers connected to filled form, are also removed, when the filled form is removed
        em.remove(attachedFilledForm);
        return true;
    }

    /**
     * Method updates in the database, specified by detachedFilledForm entity
     *
     * @param detachedFilledForm
     * @return true if operation succeeded, false - if not
     */
    @Override
    public boolean updateFilledForm(FilledForm detachedFilledForm) {
        FilledForm attachedFilledForm = em.find(FilledForm.class, detachedFilledForm.getId());
        if (null == attachedFilledForm) {
            System.out.println("FilledFormBean:updateFilledForm():FilledForm, you have specified, doesn't exist in the database!");
            return false;
        }
        em.merge(detachedFilledForm);
        return true;
    }

    /**
     * Method returns all FilledForm entities from the database
     *
     * @return all FilledForm from the database
     */
    @Override
    public List<FilledForm> getFilledForms() {
        return em.createQuery("select filledForm from FilledForm filledForm order by filledForm.whenFilled desc", FilledForm.class).getResultList();
    }

    /**
     * Method find in the detabase entity specified by id parameter, and returns
     * this entity
     *
     * @param id
     * @return founded FilledForm
     */
    @Override
    public FilledForm getFilledForm(Long id) {
        FilledForm attachedFilledForm = em.find(FilledForm.class, id);
        if (null == attachedFilledForm) {
            System.out.println("FilledFormBean:getFilledForm():FilledForm, you have specified, doesn't exist in the database!");
            return null;
        }
        return attachedFilledForm;
    }

    //TODO: This method behaviour is hard to understend, becouse this method is returning FilledForm only if it is not filled. That kind of decision should by made by the servlet instead of the EJB
    /**
     * Method finds in the detabase entity specified by linkHash parameter, and
     * returns this entity
     *
     * @param linkHash
     * @return founded FilledForm
     */
    @Override
    public FilledForm getFilledForm(String linkHash) {
        try {
            FilledForm filledForm = em.createQuery("select f from FilledForm f where f.formWasFilled=FALSE and f.linkHash=:linkHash", FilledForm.class).setParameter("linkHash", linkHash).getSingleResult();
            if (null == filledForm) {
                System.out.println("FilledFormBean:getFilledForm():FilledForm, you have specified, doesn't exist in the database!");
                return null;
            }
            return filledForm;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Method returns the raport, containing data of last 100 created filledForm
     * linked with one specified by param form, Form entity
     *
     * @param form
     * @return raport saved
     */
    @Override
    public List<FilledForm> getLastlyCreatedFilledForms(Form form, int numberOfRecords) {
        List<FilledForm> filledForms = null;

        try {
            filledForms = em.createQuery("select distinct ff from FilledForm ff inner join FormSigner fs where ff.form=:form order by ff.whenCreated desc", FilledForm.class)
                    .setParameter("form", form).setMaxResults(numberOfRecords).getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (null == filledForms || filledForms.isEmpty()) {
            System.out.println("FilledFormBean:getLastlyCreatedFilledFormData():In the database there is no FilledForms entities!");
        }

        return filledForms;
    }

}
